<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryForm" :inline="true">
        <!-- StartDate  EndDate -->
        <el-form-item label="代发状态" prop="wageStatus">
          <el-select v-model="queryForm.wageStatus" placeholder="请选择" clearable>
            <el-option v-for="item in wageStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="keywords">
          <el-input v-model="queryForm.keywords" placeholder="请输入关键字" clearable style="width: 200px" />
          <el-button type="primary" style="margin-left: 0; border-radius: 0" @click="handleQuery"> 搜索 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-button v-if="permissions.create" type="primary" size="default" icon="Plus" @click="handleCreate"
            >新增</el-button
          >
          <el-button
            v-if="permissions.templateDownload"
            type="primary"
            size="default"
            icon="Download"
            :loading="loadingTemplate"
            @click="DownloadTemplate"
            >模板下载</el-button
          >
          <el-button
            v-if="permissions.detailsDownload"
            size="default"
            icon="Download"
            type="primary"
            :loading="loadingDetails"
            @click="ExportDetails"
            >工资明细导出</el-button
          >
          <el-button v-if="permissions.importPerson" size="default" icon="Upload" @click="importPerson"
            >导入人员信息</el-button
          >
        </el-col>
        <el-col :span="24" :offset="0" style="margin-top: 10px">
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            @select="handleCurrentChange"
          >
            <el-table-column type="selection" align="center" width="50" />
            <el-table-column label="序号" type="index" :index="(index: number) => index + 1" min-width="50" />
            <el-table-column label="流水号" prop="code" min-width="200" align="center" />
            <el-table-column label="工资单名称" prop="name" min-width="200" align="center" />
            <el-table-column label="工资单类型" prop="wageTypeName" min-width="100" align="center" />
            <el-table-column label="企业名称" prop="corpName" min-width="120" align="center" />
            <el-table-column label="工资结算模式" prop="payTypeName" min-width="120" align="center" />
            <el-table-column label="工资代发状态" prop="wageStatusName" min-width="120" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.wageStatus === 0" type="info">{{ scope.row.wageStatusName }}</el-tag>
                <el-tag v-if="scope.row.wageStatus === 1">{{ scope.row.wageStatusName }}</el-tag>
                <el-tag v-if="scope.row.wageStatus === 2" type="warning">{{ scope.row.wageStatusName }}</el-tag>
                <el-tag v-if="scope.row.wageStatus === 3" type="success">{{ scope.row.wageStatusName }}</el-tag>
                <el-tag v-if="scope.row.wageStatus === 4" type="danger">{{ scope.row.wageStatusName }}</el-tag>
                <el-tag v-if="scope.row.wageStatus === -1" type="info">{{ scope.row.wageStatusName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="审核类型" prop="auditTypeName" min-width="90" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.auditType === 0">{{ scope.row.auditTypeName }}</el-tag>
                <el-tag v-if="scope.row.auditType === 1">{{ scope.row.auditTypeName }}</el-tag>
                <el-tag v-if="scope.row.auditType === 2">{{ scope.row.auditTypeName }}</el-tag>
                <el-tag v-if="scope.row.auditType === 3" type="success">{{ scope.row.auditTypeName }}</el-tag>
                <el-tag v-if="scope.row.auditType === -1" type="danger">{{ scope.row.auditTypeName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="代发月份" prop="wageMonth" min-width="100" align="center" />
            <el-table-column label="银行名称" prop="bankName" min-width="100" />
            <el-table-column label="当月计价总额" prop="totalValuation" min-width="120" align="center" />
            <el-table-column label="工资录入人数" prop="numberPeople" min-width="120" align="center" />
            <el-table-column label="申请发放金额" prop="amountApplied" min-width="120" align="center" />
            <el-table-column label="代发批次号" prop="batchNo" min-width="120" align="center" />
            <el-table-column label="操作" fixed="right" width="250">
              <template #default="scope">
                <el-button
                  v-if="permissions.update && scope.row.isEdit"
                  type="primary"
                  link
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  修改
                </el-button>
                <!-- v-if="permissions.submit && scope.row.isSubimt" -->
                <el-button
                  v-if="permissions.submit && scope.row.isSubimt"
                  type="primary"
                  link
                  size="small"
                  @click="handleSubmit(scope.row)"
                >
                  提交
                </el-button>
                <el-button
                  v-if="permissions.audit && scope.row.isAudit"
                  type="primary"
                  link
                  size="small"
                  @click="handleAudit(scope.row)"
                >
                  审核
                </el-button>
                <el-button
                  v-if="permissions.wagedetail && scope.row.isSubimt"
                  type="primary"
                  link
                  size="small"
                  @click="handleWageDetail(scope.row)"
                >
                  工资明细
                </el-button>
                <el-button
                  v-if="permissions.delete && scope.row.isDelete"
                  type="primary"
                  link
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
                <el-button v-if="permissions.detail" type="primary" link size="small" @click="handleDetail(scope.row)">
                  详情
                </el-button>
                <!-- v-if="permissions.detail && scope.row.wageStatus > 1" -->
                <el-button
                  v-if="permissions.detail && scope.row.wageStatus >= 1"
                  type="primary"
                  link
                  size="small"
                  @click="handleIssueDetail(scope.row)"
                >
                  代发详情
                </el-button>
                <el-button
                  v-if="
                    permissions.payment &&
                    scope.row.auditStatus == 1 &&
                    (!scope.row.hasCreateBatch || scope.row.wageStatus == -1)
                  "
                  type="primary"
                  link
                  size="small"
                  @click="handleCreatePayment(scope.row)"
                >
                  创建银行批量代发
                </el-button>
                <el-button
                  v-if="
                    permissions.payment &&
                    scope.row.auditStatus == 1 &&
                    scope.row.hasCreateBatch &&
                    !scope.row.hasSubmit &&
                    scope.row.wageStatus != -1
                  "
                  type="primary"
                  link
                  size="small"
                  @click="handleSubmitPayment(scope.row)"
                >
                  提交银行批量代发
                </el-button>
                <el-button
                  v-if="
                    permissions.payment &&
                    scope.row.auditStatus == 1 &&
                    scope.row.hasCreateBatch &&
                    !scope.row.hasSubmit &&
                    scope.row.wageStatus != -1
                  "
                  type="primary"
                  link
                  size="small"
                  @click="handleUnDoPayment(scope.row)"
                >
                  撤销银行批量代发
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryForm.pageNum"
            v-model:limit="queryForm.pageSize"
            @pagination="handleQuery"
          />
        </el-col>
      </el-row>
    </div>
    <add-form v-if="dialogAddOrEdit.visible" :dialog-add-or-edit="dialogAddOrEdit" @send-close="sendClose" />
    <detail v-if="dialogDetail.visible" :dialog-detail="dialogDetail" @send-close="sendClose" />
    <issue-detail v-if="dialogIssueDetail.visible" :dialog-issue-detail="dialogIssueDetail" @send-close="sendClose" />
    <import-excel
      v-if="dialogImportExcel.visible"
      :dialog-import-excel="dialogImportExcel"
      @send-close="sendCloseImportExcel"
    ></import-excel>
  </div>
</template>
<script setup lang="ts">
import addForm from "./addForm.vue";
import detail from "./detail.vue";
import issueDetail from "./issueDetail.vue";
import importExcel from "./ImportExcel/index.vue";

import { getDicts } from "@/store/modules/dict";

import {
  QueryPayrollPage,
  DeletePayroll,
  SubmitPayroll,
  ExportPayrollDetail,
  ExportPayrollTemplate,
  CreatePaymentWages,
  SubmitPaymentWages,
  UnDoPaymentWages,
} from "@/api/wage/index";
import { downloadFile } from "@/utils";
import { ElFormItem, ElUpload } from "element-plus";

const wageStatusOptions = ref(getDicts("wageStatus"));

const permissions = ref({
  create: true,
  update: true,
  delete: true,
  detail: true,
  wagedetail: true,
  submit: true,
  audit: true,
  templateDownload: true,
  detailsDownload: true,
  importPerson: true,
  payment: true,
});

const currentSystem = ref(localStorage.getItem("usertypeName"));
const isLumpContractor = ref(localStorage.getItem("isLumpContractor"));
if (currentSystem.value == "SysUser" || currentSystem.value == "Commander") {
  permissions.value = {
    create: false,
    update: false,
    delete: false,
    wagedetail: false,
    submit: false,
    audit: false,
    detail: true,
    templateDownload: false,
    detailsDownload: false,
    importPerson: false,
    payment: true,
  };
}

if (currentSystem.value == "Constructor") {
  permissions.value = {
    create: false,
    update: false,
    delete: false,
    wagedetail: false,
    submit: false,
    audit: true,
    detail: true,
    templateDownload: false,
    detailsDownload: false,
    importPerson: false,
    payment: false,
  };
}

const loading = ref(false);
const loadingTemplate = ref(false);
const loadingDetails = ref(false);
const tableData = ref();

const dialogAddOrEdit = reactive<DialogOption>({
  visible: false,
});
const dialogDetail = reactive<DialogOption>({
  visible: false,
  type: 0, //0:详情 1:工资明细 2:审核
});
const dialogImportExcel = reactive<DialogOption>({
  visible: false,
});
const dialogIssueDetail = reactive<DialogOption>({
  visible: false,
});
//当前选中项
const currentItem = ref(null as any);
const tableRef = ref();

//新增
const handleCreate = function () {
  dialogAddOrEdit.visible = true;
  dialogAddOrEdit.footBtn = "确认新增";
  dialogAddOrEdit.title = "新增";
};
//编辑
const handleEdit = function (row: any) {
  dialogAddOrEdit.visible = true;
  dialogAddOrEdit.id = row.id;
  dialogAddOrEdit.footBtn = "确认修改";
  dialogAddOrEdit.title = "修改";
};

//实现复选框的单选
const handleCurrentChange = function (selections: any, row: any) {
  if (selections.length > 1) {
    // 把数组的第一个元素从其中删除
    let del_row = selections.shift();
    // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
    tableRef.value.toggleRowSelection(del_row, false);
    currentItem.value = selections[0];
  } else {
    currentItem.value = selections[0];
  }
  if (selections.length == 0) {
    currentItem.value = null;
  }
};

//下载模板
const DownloadTemplate = (row: any) => {
  if (currentItem.value == null) {
    ElMessage({
      type: "error",
      message: "请选择需要下载的模板的工资单",
    });
    return;
  }
  loadingTemplate.value = true;
  ExportPayrollTemplate(currentItem.value.id)
    .then((res) => {
      downloadFile(res);
    })
    .finally(() => {
      loadingTemplate.value = false;
    });
};
//导出明细
const ExportDetails = async (row: any) => {
  if (currentItem.value == null) {
    ElMessage({
      type: "error",
      message: "请选择需要导出的工资单的明细",
    });
    return;
  }
  loadingDetails.value = true;
  ExportPayrollDetail(currentItem.value.id)
    .then((res) => {
      downloadFile(res);
    })
    .finally(() => {
      loadingDetails.value = false;
    });
};
//导入人员
const importPerson = function () {
  if (currentItem.value == null) {
    ElMessage({
      type: "error",
      message: "请选择需要导入的工资单",
    });
    return;
  }
  if (!currentItem.value?.isEdit) {
    ElMessage({
      type: "error",
      message: "该工资单当前状态不允许导入人员",
    });
    return;
  }
  dialogImportExcel.id = currentItem.value.id;
  dialogImportExcel.visible = true;
  dialogImportExcel.title = "导入人员信息";
};

//发放详情
const handleIssueDetail = function (row: any) {
  dialogIssueDetail.visible = true;
  dialogIssueDetail.id = row.id;
  dialogIssueDetail.title = "工资单代发详情";
};

//详情
const handleDetail = function (row: any) {
  dialogDetail.visible = true;
  dialogDetail.id = row.id;
  dialogDetail.title = "详情";
  dialogDetail.type = 0;
};
//删除
const handleDelete = function (row: any) {
  ElMessageBox.confirm("确定删除该工资单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      DeletePayroll(row.id).then((res) => {
        if (res.type === 0) {
          if (res.success) {
            ElMessage({
              type: "success",
              message: res.msg,
            });
            handleQuery();
          } else {
            ElMessage({
              type: "error",
              message: res.msg,
            });
          }
        }
      });
    })
    .catch(() => {
      console.log("取消");
    });
};
/**
 * 一键代发工资单
 */
const handleCreatePayment = function (row: any) {
  ElMessageBox.confirm("确定创建银行批量代发工资单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      CreatePaymentWages(row.id)
        .then((res) => {
          if (res.type === 0) {
            if (res.success) {
              ElMessage({
                type: "success",
                message: res.msg,
              });
              handleQuery();
            } else {
              ElMessage({
                type: "error",
                message: res.msg,
              });
            }
          }
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      console.log("取消");
    });
};

const handleSubmitPayment = function (row: any) {
  ElMessageBox.confirm("确定提交银行批量代发工资单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      SubmitPaymentWages(row.id)
        .then((res) => {
          if (res.type === 0) {
            if (res.success) {
              ElMessage({
                type: "success",
                message: res.msg,
              });
              handleQuery();
            } else {
              ElMessage({
                type: "error",
                message: res.msg,
              });
            }
          }
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      console.log("取消");
    });
};

const handleUnDoPayment = function (row: any) {
  ElMessageBox.confirm("确定撤销银行批量代发工资单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      UnDoPaymentWages(row.id)
        .then((res) => {
          if (res.type === 0) {
            if (res.success) {
              ElMessage({
                type: "success",
                message: res.msg,
              });
              handleQuery();
            } else {
              ElMessage({
                type: "error",
                message: res.msg,
              });
            }
          }
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      console.log("取消");
    });
};

//工资明细
const handleWageDetail = function (row: any) {
  dialogDetail.id = row.id;
  dialogDetail.title = "工资明细";
  dialogDetail.footBtn = "提交";
  dialogDetail.type = 1;
  dialogDetail.visible = true;
};

//审核
const handleAudit = function (row: any) {
  dialogDetail.id = row.id;
  dialogDetail.title = "审核";
  dialogDetail.footBtn = "确认审核";
  dialogDetail.type = 2;
  dialogDetail.visible = true;
};
//关闭弹窗
const sendClose = function (needRefresh: boolean) {
  dialogAddOrEdit.visible = false;
  dialogAddOrEdit.id = undefined;
  dialogDetail.visible = false;
  dialogDetail.id = undefined;
  dialogImportExcel.visible = false;
  dialogImportExcel.id = undefined;
  dialogIssueDetail.visible = false;
  dialogIssueDetail.id = undefined;
  if (needRefresh) {
    handleQuery();
  }
};
const sendCloseImportExcel = (needRefresh: boolean, needSubmit: boolean) => {
  dialogImportExcel.visible = false;
  if (needSubmit) {
    dialogDetail.id = dialogImportExcel.id;
    dialogDetail.title = "工资单提交";
    dialogDetail.footBtn = "提交";
    dialogDetail.type = 3;
    dialogDetail.visible = true;
  }
  if (needRefresh) {
    handleQuery();
  }
};

//提交
const handleSubmit = function (row: any) {
  dialogDetail.id = row.id;
  dialogDetail.title = "工资单提交";
  dialogDetail.footBtn = "提交";
  dialogDetail.type = 3;
  dialogDetail.visible = true;
  // ElMessageBox.confirm("确定提交该工资单吗？", "提示", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning",
  // })
  //   .then(() => {
  //     SubmitPayroll(row.id).then((res) => {
  //       if (res.type === 0) {
  //         if (res.success) {
  //           ElMessage({
  //             type: "success",
  //             message: res.msg,
  //           });
  //           handleQuery();
  //         } else {
  //           ElMessage({
  //             type: "error",
  //             message: res.msg,
  //           });
  //         }
  //       }
  //     });
  //   })
  //   .catch(() => {
  //     console.log("取消");
  //   });
};

//查询条件
const queryForm = reactive({
  wageStatus: null,
  keywords: "",
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0);

//这是列表数据
const handleQuery = function () {
  loading.value = true;
  QueryPayrollPage(queryForm)
    .then((res) => {
      if (res.type === 0) {
        if (res.success) {
          tableData.value = res.data.list;
          queryForm.pageNum = res.data.pageNum;
          queryForm.pageSize = res.data.pageSize;
          total.value = res.data.total;
        } else {
        }
      } else {
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  handleQuery();
});
</script>
<style scoped>
:deep(.el-button) {
  margin-left: 5px;
}
:deep(.el-input__wrapper) {
  border-radius: 0;
}
</style>
